<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Account extends Controller_Initial_Page {

    /*	public function action_tmpadd()
	{
		$user = ORM::factory('user');
		
		$data = array('username'=>'test',
                              'password'=>'test1234',
                              'password_confirm' => 'test1234',
                              'email'=>'kontakt@coderitual.com');
					  	
		$user->values($data);
 		$user->save();
 
		$login_role = new Model_Role(array('name' =>'login'));
		$user->add('roles',$login_role);
	} */

    
	public function action_ajax_login()
	{
            if ($_POST) 
            {
                $remember = array_key_exists('remember', $_POST);

                $login_correct = Auth::instance()->login($_POST['login'], $_POST['password'], $remember);
                if ($login_correct)
                {
                    $content = Request::factory('index/index')->execute();
                    $output = array('success' => true,
                                    'message' => __('Welcome in myde.sk'),
                                    'description' => __('Let\'s change the world together'),
                                    'content' => $content->__toString()); 
                }
                else
                {
                    $output = array('success' => false,
                                    'message' => __('You could not be logged'),
                                    'errors'  => array('login'    => __('Wrong Username/Email and password combination.'),
                                                       'password' => ''));
                }

                $this->response->body(json_encode($output));
            }
	}
        
        public function action_logout()
        {
            Auth::instance()->logout();
            Request::current()->redirect('/');
        }
        
        public function action_ajax_recover_password()
        {
            if ($_POST)
            {
               
                $user_model = ORM::factory('user')->where('email', '=', $_POST['e_mail'])->find();
         
                if ($user_model->loaded())
                {
                    $user_model->recovery_token = $user_model->uniqe_recovery_token(32);                   
                    $user_model->update();
                    
                    
                    //get messages
                    $email_title_message = Kohana::message('email', 'recovery_question.title');
                    
                    //translate messages
                    $email_title_message = __($email_title_message);
                
                    $email_template_view = View::factory('email/template');
                    $email_content_view = View::factory('email/change_password_request');
                    $email_content_view->set('url', URL::site('account/recover_password/'.$user_model->recovery_token, TRUE));
                    $email_content_view->set('profile', $user_model->user_profile);
                    $email_template_view->set('title', $email_title_message);
                    $email_template_view->set('content', $email_content_view);
                       
                    
                    $main_config = Kohana::config('main');
                    
                    $send_email = Email::factory($email_title_message)
                                    ->message($email_template_view, 'text/html')
                                    ->to($_POST['e_mail'])
                                    ->from($main_config->contact_mail, $main_config->contact_name)
                                    ->send();
                    if ($send_email)
                    {
                        $output = array('success'=>'true','message'=>'');
                    }
                    else
                    {
                        // there is a problem with e-mail send
                        $output = array('success'=>'false','message'=>'');
                        Log::instance()->add(Log::ERROR, 'Recovery message could not be sent');
                        
                    }       
                }
                else
                {
                    // e-mail not found 
                    $output = array('success' => 'false',
                                    'message' => __('Oh snap! We couldn\'t find you'),
                                    'errors'  => array('e_mail' => __('Perhaps you make a mistake')));
                }
                
                $this->response->body(json_encode($output));
            }
        }
        
        public function action_recover_password($token)
        {      
            
            $user_model = ORM::factory('user')->where('recovery_token', '=', $token)                                          
                                              ->find();
            if ($user_model->loaded())
            {
                $new_password = Security::generate_token(8);
                
                // new password will be automaticaly hashed by filters action 
                $user_model->recovery_token = null;
                $user_model->password = $new_password;
                $user_model->save();
                
                //get messages
                $email_title_message = Kohana::message('email', 'recovery_password.title');
                //$email_content_message = Kohana::message('email', 'recovery_password.content');
                    
                //translate messages
                $email_title_message = __($email_title_message);
//                $email_content_message = __($email_content_message,array(
//                        ':new_password' => $new_password,
//                        ':homepage' => URL::site('/', TRUE)));
                
                
                $email_template_view = View::factory('email/template');
                $email_content_view = View::factory('email/new_password_info');
                $email_content_view->set('new_password',$new_password);
                $email_template_view->set('title', $email_title_message);
                
                $email_template_view->set('content', $email_content_view);
                
                
                $main_config = Kohana::config('main');
                
                $send_email = Email::factory($email_title_message)
                              ->message($email_template_view, 'text/html')
                              ->to($user_model->email)
                              ->from($main_config->contact_mail, $main_config->contact_name)
                              ->send();
                if ($send_email)
                {
                     $content_view = View::factory('toolbar');
                     $content_view->set('content', View::factory('account/new_password_info'));      
                    $this->template->set('body',$content_view);
                }
                else
                {
                    // there is a problem with e-mail send                    
                    Log::instance()->add(Log::ERROR, 'Recovery password message could not be sent');
                    throw new HTTP_Exception_404();
                }
            }
            else
            {
                //there is no record with this hash and email 
                throw new HTTP_Exception_404();
            }
            
        }
        
        public function action_create_account($token)
        {
                 //     $session = Session::instance();
                 // $session->delete('account_data');
           
            $invitation_model = ORM::factory('invitation');  
            $invitation_model->where('token', '=', $token)->find();
            
            if($invitation_model->loaded())
            {
                $user_model = ORM::factory('user');
                $already_registered = $user_model->where('email', '=', $invitation_model->email)
                                                 ->find()
                                                 ->loaded();
                
                if($already_registered)
                {
                    //show message that for account is already registered or 404
                   throw new HTTP_Exception_404();
                }
                else
                {
                    $field_model = ORM::factory('field');
                    $country_model = ORM::factory('country');
                                          
                    $session = Session::instance();
                    if (!$session->get('account_data'))
                    {
                        $part = 1;
                    }
                    else
                    {
                        $part = 2;
                    }
                    //show register wizard 
                    $create_view = View::factory('account/create');
                    $create_view->set('part',$part);
                    $create_view->set('email',$invitation_model->email);
                    $create_view->set('token',$token);
                    $create_view->set('fields', $field_model->get_all());
                    $create_view->set('countries', $country_model->get_all());
                    $body = View::factory('content');
                    $body->set('content',$create_view);      
                                    
                }
                
                $this->template->set('body',$body);
            }
            else
            {
                 throw new HTTP_Exception_404();
            }
                       
        }
        
        public function action_ajax_create_account($token)
        {
            if ($_POST)
            {
                $invitation_model = ORM::factory('invitation');  
                $invitation_model->where('token', '=', $token)->find();

                if ($invitation_model->loaded())
                {
                    $session = Session::instance();

                    // step 1
                    if (!$session->get('account_data'))
                    {
                        //first validation
                        $user_model = Model::factory('user');
 
                        
                        $validation = Validation::factory($_POST)
                                      ->rule('name', 'not_empty')
                                      ->rule('surname',  'not_empty')
                                      ->rule('username', 'not_empty')
                                      ->rule('username', 'min_length', array(':value', 4))
                                      ->rule('username', 'max_length', array(':value', 32))
                                      ->rule('username', 'regex', array(':value', '/^[-\pL\pN_.]++$/uD'))
                                      ->rule('username', array($user_model, 'username_available'), array(':validation', ':field'))
                                      ->rule('password', 'not_empty')
                                      ->labels(array('name'    => __('Name'),
                                                     'surname' => __('Surname'),
                                                     'username'=> __('Username'),
                                                     'password'=> __('Password')));
                        if ($validation->check())
                        {
                             $_POST['email'] = $invitation_model->email;
                             $session->set('account_data', $_POST);
                             $output = array('success' => 'true',
                                             'message' => __('Great! Now create your profile'));
                        }
                        else
                        {
                              $output = array('success' => 'false',
                                              'message' => __('Holy cow, something wrong'),
                                              'errors'  => $validation->errors('validation'));
                        }
                    }
                    //step 2
                    else
                    {
                        
                        //prepare _POST variable
                        $_POST = array_merge($_POST, $session->get('account_data'));
                      //  var_dump($_POST); 
                        $date = new DateTime();
                            
                        if ($_POST['currently'] == '0')
                        {
                            $date->setDate($_POST['exp_start_date_year'], $_POST['exp_start_date_month'], 1);
                        }
                        else
                        {
                            $date->setDate($_POST['edu_start_date_year'], $_POST['edu_start_date_month'], 1);
                        }
            
                        $fields = array_key_exists('field',$_POST) ? $_POST['field'] : null; //all selected fields
                        
                        $_POST['date_start'] = $date->format('Y-m-d H:i:s');                            
                        $_POST['field'] = array_key_exists('field',$_POST) AND !empty($_POST['field']);
                        $_POST['country_iso'] = $_POST['country'];   
                         //prepare extra validation rules   
                        $extra_rules = Validation::factory($_POST);
                        $extra_rules->rule('field', 'not_empty')
                                    ->rule('address', 'not_empty')
                                    ->rule('address', 'max_length', array(':value', 127))
                                    ->rule('birth_date', 'not_empty')
                                    ->rule('birth_date', 'date')
                                    ->rule('country_iso', 'not_empty');
                        
                               
                        switch($_POST['currently'])
                        {
                            case 0:                                                                   
                                $extra_rules->rule('employer', 'not_empty')
                                            ->rule('employer', 'max_length', array(':value', 255))   
                                            ->rule('position', 'not_empty')
                                            ->rule('position', 'max_length', array(':value', 255))
				            ->rule('date_start', 'not_empty')
                                            ->rule('date_start', 'date');
                                
                                $_POST['description'] = $_POST['position'].' '.__('in').' '.$_POST['employer'];
                                break;
                                
                            case 1:
                                $extra_rules->rule('degree', 'not_empty')
                                            ->rule('degree', 'max_length', array(':value', 127)) 
                                            ->rule('school', 'not_empty')
                                            ->rule('school', 'max_length', array(':value', 255))   
                                            ->rule('faculty', 'not_empty')
                                            ->rule('faculty', 'max_length', array(':value', 255))
				            ->rule('date_start', 'not_empty')
                                            ->rule('date_start', 'date');
                                
                                $_POST['description'] = __('Student').', '.$_POST['school'];
                                break;
                                
                            case 2:                               
                            default:
                                $extra_rules->rule('description', 'not_empty')
                                            ->rule('max_length', 'max_length', array(':value', 127));
                                break;
                        }
                        
                        //prepare extra labels
                        $extra_rules->labels(array('field'      => __('Field'),
                                                   'address'    => __('Locality'),
                                                   'birth_date' => __('Date of birth'),
                                                   'degree'     => __('Degree'),
                                                   'employer'   => __('Employer'),
                                                   'position'   => __('Position'),
                                                   'school'     => __('School name'),
                                                   'faculty'    => __('Faculty'),
                                                   'date_start' => __('Start date'),
                                                   'description'=> __('My description')));                            
                        
                        //start transation
                        $db = Database::instance();
                        $db->begin();
                        
                        try
                        {
                            //create account
                            $user_model = ORM::factory('user'); 
                            $user_model->values($_POST, array('username','email','password'));
                            $user_model->save($extra_rules);
                            
                            //add role to account
                            $role_model = ORM::factory('role',array('name' =>'login'));
                            $user_model->add('roles',$role_model);
                            
                            //add fields to account
                            $user_model->add('fields',$fields);
                            
                            //create profile 
                            $user_profile_model = $user_model->user_profile; 
                    
                            $_POST['user_id'] = $user_model->id;
                            $_POST['url'] = URL::title($_POST['name'].' '.$_POST['surname'],'-',true);
                           
                            
                            $user_profile_model->values($_POST, array('name',
                                                                      'surname',
                                                                      'url',
                                                                      'description',
                                                                      'address',
                                                                      'birth_date',                                                   
                                                                      'user_id',
                                                                      'country_iso')); 

                            $user_profile_model->save();
                             
                             //create desktop
                            $user_desktop_model = $user_model->desktop;
                            $user_desktop_model->user_id = $user_model->id;
                            $user_desktop_model->color = '304580';
                            $user_desktop_model->save();
                            
                            //create notice entre
                            $notice_model = ORM::factory('notice');
                            $notice_model->user_id = $user_model->id;
                            $notice_model->save();
                            
                            //add friend to your account
                            $contact_model = ORM::factory('contact');
                            $contact_model->sender_id = $invitation_model->user_id;
                            $contact_model->recipient_id = $user_model->id;
                            $contact_model->status = 1;
                            $contact_model->save();
                            
                            //creat privacy data 
                            $user_privacy_model = $user_model->user_privacy;
                            $user_privacy_model->user_id = $user_model->id;
                            $user_privacy_model->save();
                            
                            //TODO: add information about added friend and 
                            //      new created account and message in inbox from us
                           
                          
                            //add education or experience
                            switch($_POST['currently'])
                            {
                                case '0':
                                    $user_experience_model = $user_model->user_experiences;
                                    $user_experience_model->values($_POST, array('employer',
                                                                                 'position',
                                                                                 'date_start',
                                                                                 'user_id'));
                                    $user_experience_model->save();
                                    break;
                                
                                case '1':
                                    $user_education_model = $user_model->user_educations;
                                    $user_education_model->values($_POST, array('degree',
                                                                                'school',
                                                                                'faculty',
                                                                                'date_start',
                                                                                'user_id'));
                                    $user_education_model->save();
                                    break;                                
                            }
                            
                            $db->commit();
                            $session->delete('account_data');
                            Auth::instance()->force_login($_POST['username']);
                            $content = Request::factory('index/index')->execute();
                            
                            $output = array('success' => 'true',
                                            'message' => __('Great! You have an account.'),
                                            'content' => $content->__toString());
                            
                            //force login to new account
       
                        }
                        catch (ORM_Validation_Exception $e)
                        {
                            $db->rollback();
                            $output = array('success' => 'false',
                                            'message' => __('Holy cow, something wrong'),
                                            'errors'  => $e->errors('validation'));
                        }
                    }

                    
                    $this->response->body(json_encode($output));
                    
                     /*
                    $_POST['email'] = $invitation_model->email;
                    
                    $user_model = ORM::factory('user');
                    $user_model->values($_POST,array('username','email','password'));
                    
                    $external_values = array('name'    => $_POST['name'],
                                             'surname' => $_POST['surname']);
                    $extra_rules = Validation::factory($external_values)
                                   ->rule('name', 'not_empty')
                                    ->rule('surname', 'not_empty')
                                   ->labels(array('name'   => __('Name'),
                                                  'surname' => __('Surname')));
                   
                    try
                    {
                        $user_model->save($extra_rules);
                        
                    }
                    catch (ORM_Validation_Exception  $e)
                    {
                        
                    } */
                }
            }
            
        }
     
        public function action_ajax_send_invitation()
        {
            
            if ($_POST)
            {
                //TODO: take value from config file or database;
                $max_invitation_amount = 5;
                
                $user_model = Auth::instance()->get_user();
                $invitation_model = $user_model->invitations;
                $my_amount_invitation = $invitation_model->count_all();                                
                
                if ($my_amount_invitation < $max_invitation_amount)
                {
                   
                   $_POST['token'] = $invitation_model->uniqe_invitation_token(32);
                   $_POST['user_id'] = $user_model->id;
                   $invitation_model->values($_POST, array('email','token','user_id')); 
                   
                   try
                   {
                        $invitation_model->save();

                        //get messages
                        $email_title_message = Kohana::message('email', 'invitation.title');
                       // $email_content_message = Kohana::message('email', 'invitation.content');
                    
                        //translate messages
                        $email_title_message = __($email_title_message, array(
                            ':name' => $user_model->user_profile->name.' '.$user_model->user_profile->surname
                        ));
                    /*    $email_content_message = __($email_content_message, array(
                            ':link' => URL::site('account/create_account/'.$_POST['token'], TRUE),
                            ':name' => $user_model->user_profile->name.' '.$user_model->user_profile->surname
                        )); */
                        
                        // TODO: add more fields , create e-mail message 
                        $email_template_view = View::factory('email/template');
                        $email_content_view = View::factory('email/invitation_to_app');
                        $email_content_view->set('url',URL::site('account/create_account/'.$_POST['token'], TRUE));
                        $email_content_view->set('user',$user_model);
                        $email_template_view->set('title', $email_title_message);
                        $email_template_view->set('content', $email_content_view);
                                         
                        $main_config = Kohana::config('main');
                    
                        $send_email = Email::factory($email_title_message)
                                      ->message($email_template_view, 'text/html')
                                      ->to($_POST['email'])
                                      ->from($main_config->contact_mail, $main_config->contact_name)
                                      ->send();
                        if ($send_email)
                        {
                            $output = array('success' => 'true',
                                            'message' => __('Ivitation has been sent'));                            
                        }
                        else
                        {
                            // there is a problem with e-mail send
                            $output = array('success' => 'false',
                                            'message' => __('System went shopping, try later'),
                                            'errors'  => array());
                            Log::instance()->add(Log::ERROR, 'Recovery message could not be sent');
                        }
                            
                    }
                    catch (ORM_Validation_Exception $e)
                    {
                        $output = array('success' => 'false',
                                        'message' => __('oh bloody hell'),
                                        'errors'  => $e->errors('validation'));
                    }
                                                                           
                    $this->response->body(json_encode($output));
                }
               
            }
        }
        
        public function action_show_profile($url)
        {        
            $user_model = ORM::factory('user');
            $user_model->with('user_profile:country')
                       ->where('url','=',$url)
                       ->find();
            
            $my_user_model  = Auth::instance()->get_user();
 
            if(!$user_model->loaded())
                    throw new HTTP_Exception_404;
                   
            $privacy = Privacy::factory($my_user_model ? $my_user_model->id : false,
                                        $user_model->id);        
            
            $send_message_permission = $privacy->send_message_permission();
            $send_invitation_permission = $privacy->send_invitation_permission();
            
            
            //check permision to view profile
            if($privacy->view_profile_permission())
            { 
                //get all mutual friends             
                $mutual_friends = false;
                if ($my_user_model)
                {
                    $contact_model = ORM::factory('contact');   
                    $mutual_friends = $contact_model->get_mutual_friends(($my_user_model) ? $my_user_model->id : false,
                                                                          $user_model->id);
                }

                //get all user contacts
                $contact_model = ORM::factory('contact');
                $contacts = $contact_model->get_contacts($user_model->id);
                
                $account_profile_view = View::factory('account/profile');
                $account_profile_view->set('additional', $user_model->user_additional)
                                     ->set('experiences', $user_model->user_experiences->order_by('date_start','DESC')->find_all())
                                     ->set('educations', $user_model->user_educations->find_all())
                                     ->set('contacts', $contacts)
                                     ->set('mutual_friends', $mutual_friends);
            }
            else
            {
                $account_profile_view = $my_user_model ? View::factory('account/profile_access denied') : View::factory('account/profile_unlogged');              
            }
                        
            //generate views
            $account_profile_navigation_view = View::factory('account/profile_navigation');
            
            $account_profile_navigation_view->set('add_to_contacts', $send_invitation_permission)
                                            ->set('message', $send_message_permission)
                                            ->set('profile', $user_model->user_profile);
                      
            $account_profile_view->set('profile', $user_model->user_profile) 
                                 ->set('fields', $user_model->fields->find_all())
                                 ->set('profile_navigation',$account_profile_navigation_view);
            
            $content_view = View::factory('content'); 
            $content_view->set('content', $account_profile_view );
            $this->template->set('body',$content_view);    
        }
} // End Account
